import cv2
import matplotlib.pyplot as plt
import numpy as np

def img_recover(img):
    # 灰度化
    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

    # 膨胀腐蚀
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))
    img = cv2.dilate(img, kernel)
    img = cv2.erode(img, kernel)

    # 二值化
    _, img = cv2.threshold(img, 210, 255, cv2.THRESH_BINARY_INV)
    img = cv2.dilate(img, kernel)
    img = cv2.erode(img, kernel)

    # 平移
    M = cv2.moments(img)
    epsilon = 1e-5
    cx = M["m10"] / (M["m00"] + epsilon)
    M = np.float32([[1, 0, (32-cx)], [0, 1, 0]])
    img = cv2.warpAffine(img, M, img.shape)

    return img

plt.subplot(121)
zero = '0_48.jpg'
zero = cv2.imread(zero)
plt.title("Original")
plt.imshow(zero)
plt.subplot(122)
new_zero = img_recover(zero)
plt.title("Binary")
plt.imshow(new_zero, cmap='binary')
plt.show()